package com.photoeditor.demo.ui.widget.image;

import android.content.Context;
import android.graphics.Bitmap;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.common.base.ComponentContext;
import com.common.base.ui.widget.image.RoundImageView;
import com.common.base.utils.DeviceUtils;
import com.photoeditor.R;
import com.photoeditor.demo.app.BaseRecycleViewAdapter;
import com.photoeditor.demo.db.FilterBean;
import com.photoeditor.demo.db.FilterConstant;
import com.photoeditor.demo.imageloader.GlideApp;
import com.photoeditor.demo.model.filter.ImageFilterTools;
import com.photoeditor.demo.model.preference.SPDataManager;
import com.photoeditor.demo.model.store.module.BaseOnlineManager;
import com.photoeditor.demo.model.subscribe.manager.AppVipManager;
import com.photoeditor.demo.ui.activity.edit.MediaEditBaseActivity;
import com.photoeditor.demo.ui.widget.sticker.StickerPanelDownloadView;
import com.photoeditor.demo.util.FontUtil;

import java.lang.ref.WeakReference;
import java.util.List;

/**
 * 滤镜的Adapter
 */
public class FilterRecylerAdapter extends BaseRecycleViewAdapter<FilterBean> {

    private RoundImageView mImageView;

    private final int mImageViewId = 1001;

    private boolean mShowNew;

    private Context mContext;

    public static final int MAIN_FILTER_TYPE = 1;

    public static final int Edit_FILTER_TYPE = 2;

    public static final int VIDEO_FILTER_TYPE = 3;

    public static final int COLLAGE_FILTER_TYPE = 4;

    private int mType;

    private FilterIconManager mIconManager;

    private int mSelItemIndex = -1;
    private WeakReference<View> mCurSelViewBg;//bg
    private WeakReference<View> mCurSelViewIcon; // check

    private boolean mStartAnmitioning = true;

    private boolean mShadowEnable = false;

    private int mSelectEffectType = FilterCategoryAdapter.SELECT_EFFECT_CHECK;

    private boolean mIsVip;

    private int lastPosition = 0;//上次选中的position
    private boolean inited = true;

    public void setVip(boolean vip) {
        mIsVip = vip;
    }

    /**
     * 二级页面选中背景时 √图片和背景勾选中
     */
    public void setSelectEffectType(int selectEffectType) {
        mSelectEffectType = selectEffectType;
    }

    public FilterRecylerAdapter(Context context, List<FilterBean> data, int type) {
        super();
        this.mContext = context;
        this.mData = data;
        mType = type;

        if (type == MAIN_FILTER_TYPE) {
            mImageView = new RoundImageView(context);
            mImageView.setLayoutParams(new RelativeLayout.LayoutParams(DeviceUtils.dip2px(context, 48),
                    DeviceUtils.dip2px(context, 48)));
            mImageView.setRadius(DeviceUtils.dip2px(context, 48));
            mImageView.setScaleType(ScaleType.CENTER);
            mImageView.setId(mImageViewId);
        } else if (type == Edit_FILTER_TYPE || type == VIDEO_FILTER_TYPE) {
            mIconManager = new FilterIconManager((MediaEditBaseActivity) context);
        }
        mShowNew = SPDataManager.getHasNewFilter();
    }

    public FilterRecylerAdapter(Context context, int type) {
        super();
        this.mContext = context;
        mType = type;
        mIsVip = AppVipManager.isVip();

        if (type == MAIN_FILTER_TYPE) {
            mImageView = new RoundImageView(context);
            mImageView.setLayoutParams(new RelativeLayout.LayoutParams(DeviceUtils.dip2px(context, 48),
                    DeviceUtils.dip2px(context, 48)));
            mImageView.setRadius(DeviceUtils.dip2px(context, 48));
            mImageView.setScaleType(ScaleType.CENTER);
            mImageView.setId(mImageViewId);
        } else if (type == Edit_FILTER_TYPE || type == VIDEO_FILTER_TYPE) {
            mIconManager = new FilterIconManager((MediaEditBaseActivity) context);
        }
        mShowNew = SPDataManager.getHasNewFilter();
    }

    @Override
    protected RecyclerView.ViewHolder createVHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        RelativeLayout layout = (RelativeLayout) inflater.inflate(R.layout.item_filterlist_new, parent, false);
        FilterRecylerAdapter.FilterViewHoler viewHolder = new FilterRecylerAdapter.FilterViewHoler(layout);
        return viewHolder;
    }

    @Override
    protected void showItemView(RecyclerView.ViewHolder viewholder, int position) {
        FilterViewHoler holder = (FilterViewHoler) viewholder;
        final FilterBean data = mData.get(position);
        int type = data.getType();
        holder.mItemPosition = position;
        if (mType == MAIN_FILTER_TYPE || mType == VIDEO_FILTER_TYPE || mType == COLLAGE_FILTER_TYPE) {
            if (type == FilterConstant.TYPE_DOWNLOAD || type == FilterConstant.TYPE_ARTISTIC) {
                ImageFilterTools.setImage(holder.mIcon, ComponentContext.getContext(),
                        data.getPackageName(), data.getApkUri(), data.getIcon());
            } else if (type == FilterConstant.TYPE_ORIGINAL) {
                GlideApp.with(ComponentContext.getContext())
                        .load(R.drawable.ic_original)
                        .into(holder.mIcon);
            }
        } else {
            holder.mIcon.setImageBitmap(null);
            if (type == FilterConstant.TYPE_ORIGINAL) {
                holder.mIcon.setTag(data);
                mIconManager.loadIcon(holder.mIcon, data);
            } else {
                holder.mIcon.setTag(data);
                mIconManager.loadIcon(holder.mIcon, data);
            }
        }
        holder.mName.setText(data.getName());
        if (mSelItemIndex == position) {
            holder.mSelectIcon.setVisibility(View.VISIBLE);
        } else {
            holder.mSelectIcon.setVisibility(View.GONE);
        }
        if (!mIsVip && data.isBuy()) {
            holder.mVipIcon.setVisibility(View.VISIBLE);
        } else {
            holder.mVipIcon.setVisibility(View.INVISIBLE);
        }
        setTextUI(holder.mName);
        holder.itemView.setVisibility(View.VISIBLE);
        holder.mIcon.setVisibility(View.VISIBLE);
        holder.mDownloadView.setData(data.getPackageName(), BaseOnlineManager.STORE_FUNC_TYPE_FILTER, data.getType() == FilterConstant.TYPE_ORIGINAL);

        //配合setSeletcItemPosition（）的代码刷新单个item
        if (inited && position == lastPosition){  //初次进入显示当前position为选中状态
            inited = false;
            lastPosition = position;
            holder.mSelectIcon.setVisibility(View.VISIBLE);
        }else if (lastPosition != position){
            holder.mSelectIcon.setVisibility(View.GONE);
        }else{
            holder.mSelectIcon.setVisibility(View.VISIBLE);
        }
    }

    public void setTextShadowEnable(boolean enable) {
        mShadowEnable = enable;
    }

    private void setTextUI(TextView name) {
        if (mShadowEnable) {
            name.setTextColor(name.getResources().getColor(R.color.transparent_bg_text_color));
            //name.setShadowLayer(10, 0, 1, name.getResources().getColor(R.color.transparent_bg_text_shadow_color));
        } else {
            name.setTextColor(name.getResources().getColor(R.color.white_bg_text_color));
            //name.setShadowLayer(0, 0, 0, Color.TRANSPARENT);
        }
    }

    public void setStartAnmitioning(boolean start) {
        mStartAnmitioning = start;
    }

    @Override
    public long getAdapterItemId(int position) {
        return position;
    }

    public class FilterViewHoler extends RecyclerView.ViewHolder {
        //        public RoundImageView mIcon;
        public com.photoeditor.demo.ui.widget.RoundImageView mIcon;
        public TextView mName;
        //        public View mIconBg;
//        public View mSelectBackground;
        public ImageView mSelectIcon;
        public int mItemPosition;
        public ImageView mVipIcon;
        private StickerPanelDownloadView mDownloadView;

        public FilterViewHoler(View itemView) {
            super(itemView);
            mIcon = itemView.findViewById(R.id.iv_icon);
            mName = (TextView) itemView.findViewById(R.id.tv_name);
            FontUtil.setCustomFont(mName);
//            mIconBg = itemView.findViewById(R.id.select_bg);
//            mSelectBackground = itemView.findViewById(R.id.select_background);
            mSelectIcon = itemView.findViewById(R.id.item_select_img);
            mVipIcon = itemView.findViewById(R.id.img_vip);
            mDownloadView = itemView.findViewById(R.id.download_layout);
        }
    }

    /**
     * 在onitemClick中调用
     *
     * @param seletcItemPosition
     * @param view
     */
    public void setSeletcItemPosition(int seletcItemPosition, View view, RecyclerView recyclerView) {
        mSelItemIndex = seletcItemPosition;

//        if(mSelectEffectType == FilterCategoryAdapter.SELECT_EFFECT_CHECK) {
//            if (mCurSelViewIcon != null && mCurSelViewIcon.get() != null) {
//                mCurSelViewIcon.get().setVisibility(View.GONE);
//            }
//            mCurSelViewIcon = new WeakReference<>(view.findViewById(R.id.select_bg));
//            view.findViewById(R.id.select_bg).setVisibility(View.VISIBLE);
//        } else {
//            if (mCurSelViewBg != null && mCurSelViewBg.get() != null) {
//                mCurSelViewBg.get().setVisibility(View.GONE);
//            }
//            mCurSelViewBg = new WeakReference<>(view.findViewById(R.id.select_background));
//            view.findViewById(R.id.select_background).setVisibility(View.VISIBLE);
//
//            if (mCurSelViewIcon != null && mCurSelViewIcon.get() != null) {
//                mCurSelViewIcon.get().setVisibility(View.GONE);
//            }
//            mCurSelViewIcon = new WeakReference<>(view.findViewById(R.id.select_bg));
//            view.findViewById(R.id.select_bg).setVisibility(View.VISIBLE);
//        }

        //配合刷新单个item
        if (lastPosition != seletcItemPosition) {
            FilterViewHoler holder1 = (FilterViewHoler) recyclerView.findViewHolderForLayoutPosition(lastPosition);
            if (holder1 != null) {//还在屏幕里
                holder1.mSelectIcon.setVisibility(View.GONE);  //取消选中
            } else {
                notifyItemChanged(lastPosition);
            }
            //设置新Item的勾选状态
            lastPosition = seletcItemPosition;
            FilterViewHoler holder2 = (FilterViewHoler) recyclerView.findViewHolderForLayoutPosition(lastPosition);
            holder2.mSelectIcon.setVisibility(View.VISIBLE);  //设置选中
        }
    }

    public void setSeletcItemPosition(int seletcItemPosition) {
        mSelItemIndex = seletcItemPosition;
//        if(mSelectEffectType == FilterCategoryAdapter.SELECT_EFFECT_BG) {
//            if (mCurSelViewBg != null && mCurSelViewBg.get() != null) {
//                mCurSelViewBg.get().setVisibility(View.GONE);
//            }
//
//            if (mCurSelViewIcon != null && mCurSelViewIcon.get() != null) {
//                mCurSelViewIcon.get().setVisibility(View.GONE);
//            }
//        } else {
//            if (mCurSelViewIcon != null && mCurSelViewIcon.get() != null) {
//                mCurSelViewIcon.get().setVisibility(View.GONE);
//            }
//        }

        lastPosition = 0;
        inited = true;
    }

    public int getPositionByFilterPkgName(String pkgName) {
        int ret = 0;
        if (!TextUtils.isEmpty(pkgName)) {
            for (int i = 0; i < getData().size(); i++) {
                FilterBean bean = getData().get(i);
                if (pkgName.equals(bean.getPackageName())) {
                    ret = i;
                }
            }
        }
        return ret;
    }

    /**
     * 恢复默认并刷新View会刷新View
     * 特殊处理用于编辑界面
     *
     * @param vp
     */
    public void resetSelectItemositionAndResetView(ViewGroup vp) {
        mSelItemIndex = 0;
        if (mType == Edit_FILTER_TYPE || mType == VIDEO_FILTER_TYPE || mType == COLLAGE_FILTER_TYPE) {
            int child = vp.getChildCount();
            for (int i = 0; i < child; i++) {
                View v = vp.getChildAt(i);
                View image = v.findViewById(R.id.filter_item_image);
//                Object o = image.getTag();
//                if (o != null && o instanceof FilterBean) {
//                    // TODO:
//                }
            }
        }
    }

    public int getSeletcItemPosition() {
        return mSelItemIndex;
    }

    /**
     * @param bitmap
     */
    public void setBaseBitmap(Bitmap bitmap) {
        if (mIconManager != null) {
            mIconManager.setBaseBitmap(bitmap);
            notifyDataSetChanged();
        }
    }

    public void onDestory() {
        if (mIconManager != null) {
            mIconManager.onDestory();
        }
    }

    public int getFilterIndex(String filterPackageName) {
        int i = 0;
        for (FilterBean filterBo : mData) {
            if (TextUtils.equals(filterBo.getPackageName(), filterPackageName)) {
                return i;
            }
            i++;
        }
        return -1;
    }

    public String getFilterPackageName(int index) {
        if (index < mData.size()) {
            return mData.get(index).getPackageName();
        }
        return null;
    }
}
